package com.example.weight.householdWaste;

import android.annotation.SuppressLint;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.arrayAdapter.ItemAdapter;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class StoppageClearActivity extends AppCompatActivity {

    private SharedPreferences preferences;

    private ItemAdapter adapter, adapter1;
    private List<String> nameList, nameList1;

    private String name, factory;

    private EditText part, person, comment;

    private PopupWindow popupWindow, popupWindow1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stoppage_clear);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.stoppage_clear_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

//        time = findViewById(R.id.stoppage_clear_time_text);
        part = findViewById(R.id.stoppage_part);
        person = findViewById(R.id.stoppage_clear_staff);
        comment = findViewById(R.id.stoppage_clear_comment);

        // 设置输入记录缓存
        preferences = getSharedPreferences("stoppage_clean", Context.MODE_PRIVATE);

        nameList = new ArrayList<>(preferences.getStringSet("part", new HashSet<>()));
        nameList1 = new ArrayList<>(preferences.getStringSet("person", new HashSet<>()));
        List<Item> itemList = new ArrayList<>();
        List<Item> itemList1 = new ArrayList<>();

        // Item类型list初始化
        for (String itemName : nameList) {
            itemList.add(new Item(itemName, R.drawable.ic_clear));
        }
        for (String itemName : nameList1) {
            itemList1.add(new Item(itemName, R.drawable.ic_clear));
        }

        // 创建ListView
        adapter = new ItemAdapter(this, R.layout.adapter_item, itemList);
        adapter1 = new ItemAdapter(this, R.layout.adapter_item, itemList1);
        ListView listView = new ListView(this);
        ListView listView1 = new ListView(this);
        listView.setAdapter(adapter);
        listView1.setAdapter(adapter1);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            // 若有进行删除操作，更新nameList，否则nameList序号对不上
            if (adapter.getDeletePos() >= 0) {
                List<Item> tempItemList = adapter.getList();
                nameList.clear();
                for (Item item : tempItemList) {
                    nameList.add(item.getName());
                }
            }
            // 根据所选设置输入框文本
            String result = nameList.get(position);
            part.setText(result);
            popupWindow.dismiss();
            hideInput();
        });
        listView1.setOnItemClickListener((parent, view, position, id) -> {
            if (adapter1.getDeletePos() >= 0) {
                List<Item> tempItemList = adapter1.getList();
                nameList1.clear();
                for (Item item : tempItemList) {
                    nameList1.add(item.getName());
                }
            }
            String result = nameList1.get(position);
            person.setText(result);
            popupWindow1.dismiss();
            hideInput();
        });

        // 获取屏幕的宽度并设置popupwindow的宽度为width,这里是根据布局控件所占的权重
        WindowManager wManager = (WindowManager) getSystemService(this.WINDOW_SERVICE);
        int width = wManager.getDefaultDisplay().getWidth() * 3 / 5;
        int height = wManager.getDefaultDisplay().getHeight() / 8;
        // 参数为 1.View 2.宽度 3.高度
        popupWindow = new PopupWindow(listView, width, WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow1 = new PopupWindow(listView1, width, WindowManager.LayoutParams.WRAP_CONTENT);
        // 设置点击外部区域可以取消popupWindow
        popupWindow.setOutsideTouchable(true);
        popupWindow1.setOutsideTouchable(true);

        part.setOnFocusChangeListener((v, hasFocus) -> {
            // 设置popupWindow显示,并且告诉它显示在那个View下面
            if (hasFocus) {
                // 若聚焦到该输入框，显示下拉列表
                popupWindow.showAsDropDown(part);
            }
        });
        person.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                popupWindow1.showAsDropDown(person);
            }
        });

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/shlj/blockageCleaning/findForm" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @SuppressLint({"DefaultLocale", "SetTextI18n"})
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
//                                JSONObject data = jsonObject.getJSONObject("data");
                                JSONArray datas = jsonObject.getJSONArray("data");
                                JSONObject data = datas.getJSONObject(datas.length()-1);
//                                time.setText(String.format("%02d", HOUR) + ":" + String.format("%02d",MINUTE));
                                part.setText(data.getString("blockagePosition"));
                                person.setText(data.getString("cleaningPerson"));
                                comment.setText(data.getString("remarks"));
                                Toast.makeText(StoppageClearActivity.this,
                                        "今日已填写此表", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(StoppageClearActivity.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);

//        time.setOnFocusChangeListener((v, hasFocus) -> {
//            if (hasFocus) {
//                Calendar calendar = Calendar.getInstance();
//                int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
//                int MINUTE = calendar.get(Calendar.MINUTE);
//
//                TimePickerDialog timePickerDialog = new TimePickerDialog(StoppageClearActivity.this,
//                        (view1, hourOfDay, minute) ->
//                        time.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
//                        ,HOUR
//                        ,MINUTE
//                        ,true);
//                timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                if (which == DialogInterface.BUTTON_NEGATIVE) {
//                                    //取消操作
//                                    time.clearFocus();
//                                }
//                            }
//                        });
//                timePickerDialog.show();
//            }
//        });
    }

//    public void selectTime(View view) {
//        Calendar calendar = Calendar.getInstance();
//        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
//        int MINUTE = calendar.get(Calendar.MINUTE);
//
//        new TimePickerDialog(this, (view1, hourOfDay, minute) ->
//                time.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
//                ,HOUR
//                ,MINUTE
//                ,true).show();
//    }

    public void save(View view) {
        if (part.getText().toString().equals("")) {
            Toast.makeText(this, "请填写堵塞部位", Toast.LENGTH_SHORT).show();
            return;
        }
//        if (time.getText().toString().equals("")) {
//            Toast.makeText(this, "请填写时间", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if (person.getText().toString().equals("")) {
            Toast.makeText(this, "请填写清掏人员", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
            .setTitle("确定保存吗？")
            .setCancelable(false)
            .setNegativeButton("取消", ((dialog, which) ->
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
            .setPositiveButton("确定", (dialog, which) -> {
                SharedPreferences.Editor editor = preferences.edit();
                // 若有进行删除操作，更新nameList
                List<Item> tempItemList = adapter.getList();
                List<Item> tempItemList1 = adapter1.getList();
                if (tempItemList.size() != nameList.size()) {
                    nameList.clear();
                    for (Item item : tempItemList) {
                        nameList.add(item.getName());
                    }
                }
                if (tempItemList1.size() != nameList1.size()) {
                    nameList1.clear();
                    for (Item item : tempItemList1) {
                        nameList1.add(item.getName());
                    }
                }
                // 判断该输入框内容是否已存在，不存在则加入
                String currentCheckResult = part.getText().toString();
                if (!currentCheckResult.equals("") && !nameList.contains(currentCheckResult)) {
                    nameList.add(currentCheckResult);
                }
                String currentCheckResult1 = person.getText().toString();
                if (!currentCheckResult1.equals("") && !nameList1.contains(currentCheckResult)) {
                    nameList1.add(currentCheckResult1);
                }

                editor.putStringSet("part", new HashSet<>(nameList));
                editor.putStringSet("person", new HashSet<>(nameList1));
                editor.apply();

                // 提交表单
                RequestQueue queue = Volley.newRequestQueue(this);
                String url = Config.url + "/shlj/blockageCleaning/addForm";

                StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.d("zys", response);
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String code = jsonObject.getString("code");
//                                    part.setText("");
//                                    time.setText("");
//                                    person.setText("");
//                                    comment.setText("");

                                    if (code.startsWith("2"))
                                        Toast.makeText(StoppageClearActivity.this,
                                                "保存成功", Toast.LENGTH_SHORT).show();
                                    else
                                        Toast.makeText(StoppageClearActivity.this,
                                                "保存失败", Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(StoppageClearActivity.this,
                                "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> map=new HashMap<>();
                        Calendar calendar=Calendar.getInstance();
                        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
                        String hour = String.format("%02d", HOUR);
                        int MINUTE = calendar.get(Calendar.MINUTE);
                        String minute = String.format("%02d", MINUTE);
                        map.put("time", hour+":"+minute);
                        map.put("blockage_position", part.getText().toString());
                        map.put("cleaning_person", person.getText().toString());
                        map.put("recording_person", name);
                        map.put("remarks", comment.getText().toString());
                        map.put("factory", factory);
                        return map;
                    }
                };
                stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue.add(stringRequest);
            })
            .show();
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
}
